package https

import (
	"bytes"
	"encoding/json"
	"errors"
	"gitee.com/youbeiwuhuan/go-xxljob-executor/biz/model"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"
)

const XXL_JOB_ACCESS_TOKEN = "XXL-JOB-ACCESS-TOKEN"

func PostJson(url string, jsonStr string, accessToken string, timeout time.Duration) (t []byte, err error) {
	if "" == url || "" == jsonStr {
		panic("args error")
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(jsonStr)))
	if nil != err {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept-Charset", "application/json")
	if "" != accessToken {
		req.Header.Set(XXL_JOB_ACCESS_TOKEN, accessToken)
	}

	client := &http.Client{Timeout: timeout}
	resp, err := client.Do(req)

	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()

	if 200 != resp.StatusCode {
		return nil, errors.New("PostJson resp http code:" + strconv.Itoa(resp.StatusCode))
	}

	body, err := ioutil.ReadAll(resp.Body)
	if nil != err {
		return nil, err
	}

	return body, nil
}

func PostJsonXxljob(url string, jsonStr string, accessToken string, timeout time.Duration) (t model.ReturnT) {
	if "" == url || "" == jsonStr {
		panic("args error")
	}

	body, err := PostJson(url, jsonStr, accessToken, timeout)
	if nil != err {
		return model.NewReturnT(model.FAIL_CODE, err.Error(), nil)
	}

	r := model.ReturnT{}
	err = json.Unmarshal(body, &r)
	if nil != err {
		return model.NewReturnT(model.FAIL_CODE, err.Error(), nil)
	}

	return r
}
